package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.swing.*;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class ReportServiceImpl implements ReportService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WorkspaceService workspaceService;
    /**
     * 根据时区统计营业额
     * @param begin
     * @param end
     * @return
     */
    public TurnoverReportVO turnoverStatistics(LocalDate begin, LocalDate end){
        //根据时区查询营业额,只查询那些状态是已完成的订单
        //设定dateList,存放日期
        List<LocalDate> dateList = getDateList(begin,end);
        //统计营业额相关数据,只统计相应天数的已完成
        List<Double> turnoverList = new ArrayList<>();
        Map map = new HashMap<>();
        map.put("status", Orders.COMPLETED);
        for (LocalDate localDate : dateList) {
            map.put("begin", LocalDateTime.of(localDate, LocalTime.MIN));
            map.put("end",LocalDateTime.of(localDate,LocalTime.MAX));
            Double turnover = orderMapper.sumByMap(map);//因为使用包装类型,如果那天营业额为0的话,返回的是null
            turnover = turnover == null ? 0.0 : turnover;
            turnoverList.add(turnover);
        }
        //封装数据
        //返回格式,Spring,各个日期(营业额)使用,分割
        return TurnoverReportVO.builder()
                .dateList(StringUtils.join(dateList,","))
                .turnoverList(StringUtils.join(turnoverList,","))
                .build();
    }
    /**
     * 根据时区统计新增用户数量和总用户数量
     * @param begin
     * @param end
     * @return
     */
    public UserReportVO userStatistics(LocalDate begin, LocalDate end){
        //设定dateList,存放日期
        List<LocalDate> dateList = getDateList(begin,end);
        //设定总用户
        List<Integer> toTotalUserList= new ArrayList<>();
        //设定新用户
        List<Integer> newUserList= new ArrayList<>();
        for (LocalDate localDate : dateList) {
            //设定具体时间
            LocalDateTime beginTime = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(localDate, LocalTime.MAX);
            //获取新用户数量
            Integer countNew = getUserCount(beginTime, endTime);
            //获取总用户数量,只用输入结束时间
            Integer countTotal = getUserCount(null, endTime);
            newUserList.add(countNew);
            toTotalUserList.add(countTotal);
        }
        return UserReportVO.builder()
                .dateList(StringUtils.join(dateList,","))
                .newUserList(StringUtils.join(newUserList,","))
                .totalUserList(StringUtils.join(toTotalUserList,","))
                .build();
    }

    /**
     * 根据时区获取用户数量
     * @param beginTime
     * @param endTime
     * @return
     */
    private Integer getUserCount(LocalDateTime beginTime,LocalDateTime endTime){
        //使用万能map
        Map map= new HashMap<>();
        map.put("begin",beginTime);
        map.put("end",endTime);
        //进行查询
        Integer countUser = userMapper.countByMap(map);
        return countUser;
    }

    /**
     * 获取时区内的所有日期的list
     * @param begin
     * @param end
     * @return
     */
    private List<LocalDate> getDateList(LocalDate begin,LocalDate end){
        //设定dateList,存放日期
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)){
            dateList.add(begin = begin.plusDays(1));//添加他后面的一天
        }
        return dateList;
    }
    /**
     * 订单统计
     * @param begin
     * @param end
     * @return
     */
    public OrderReportVO orderStatistics(LocalDate begin, LocalDate end){
        //设定dateList,存放日期
        List<LocalDate> dateList = getDateList(begin, end);
        //设定每日订单数和每日有效订单数
        List<Integer> orderCountList = new ArrayList<>();
        List<Integer> validOrderCountList = new ArrayList<>();
        Integer sum = 0;
        Integer vSum = 0;
        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Integer orderCount = getOrderByStatusAndDate(null,beginTime, endTime);
            orderCountList.add(orderCount);
            sum+=orderCount;
            Integer validOrderCount = getOrderByStatusAndDate(Orders.COMPLETED, beginTime, endTime);
            validOrderCountList.add(validOrderCount);
            vSum+=validOrderCount;
        }
        //设定订单完成率
        //订单完成率
        Double orderCompletionRate = 0.0;
        if (sum!=0){
            orderCompletionRate = vSum.doubleValue() / sum;
        }
        return OrderReportVO.builder()
                .dateList(StringUtils.join(dateList,","))
                .orderCountList(StringUtils.join(orderCountList,","))//每日订单数
                .validOrderCountList(StringUtils.join(validOrderCountList,","))//每日有效订单总数
                .totalOrderCount(sum)//订单总数
                .validOrderCount(vSum)//有效订单数
                .orderCompletionRate(orderCompletionRate)//订单完成率
                .build();
    }

    /**
     * 根据状态和日期查询每日订单数
     * @param status
     * @param beginTime
     * @param endTime
     * @return
     */
    private Integer getOrderByStatusAndDate(Integer status,LocalDateTime beginTime,LocalDateTime endTime){
        Map map = new HashMap();
        map.put("status",status);
        map.put("begin",beginTime);
        map.put("end",endTime);
        Integer count = orderMapper.countByMap(map);
        return count;
    }
    /**
     * 查询销量top10
     * @param begin
     * @param end
     * @return
     */
    public SalesTop10ReportVO getSalesTop10(LocalDate begin, LocalDate end){
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        List<GoodsSalesDTO> goodsSalesDTOList= orderMapper.getSaleTop10(beginTime,endTime);
        String nameList =
        StringUtils.join
                (goodsSalesDTOList.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList()),",");
        String numberist =
                StringUtils.join
                        (goodsSalesDTOList.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList()),",");
        return SalesTop10ReportVO.builder()
                .nameList(nameList)
                .numberList(numberist)
                .build();
    }
    /**
     * 导出运营数据报表
     * @param httpServletResponse
     */
    public void exportBusinessData(HttpServletResponse httpServletResponse){
        //查询数据库,得到近30天的营业数据
        LocalDate begin = LocalDate.now().minusDays(30);
        LocalDate end = LocalDate.now().minusDays(1);
        //查询概览数据
        BusinessDataVO businessData = workspaceService.
                getBusinessData(LocalDateTime.of(begin, LocalTime.MIN), LocalDateTime.of(end, LocalTime.MAX));
        //使用POI将数据写入到Excel文件当中
        InputStream is = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
        try {
            //基于模板文件创建一个新的Excel文件
            XSSFWorkbook excel = new XSSFWorkbook(is);
            //获得表格文件的sheet页
            XSSFSheet sheet = excel.getSheet("sheet1");
            //填充数据:时间
            XSSFRow row = sheet.getRow(1);
            row.getCell(1).setCellValue("时间: "+begin+"->"+end);
            //获取第四行
            row = sheet.getRow(3);
            row.getCell(2).setCellValue(businessData.getTurnover());
            row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
            row.getCell(6).setCellValue(businessData.getNewUsers());
            //获取第五行
            row = sheet.getRow(4);
            row.getCell(2).setCellValue(businessData.getValidOrderCount());
            row.getCell(4).setCellValue(businessData.getUnitPrice());
            //填充明细数据
            for (int i = 0; i < 30; i++) {
                LocalDate date = begin.plusDays(i);//从三十天开始,一天一天获取数据
                BusinessDataVO data =
                        workspaceService.getBusinessData(LocalDateTime.of
                                (date, LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));
                row = sheet.getRow(7+i);
                //写入数据
                row.getCell(1).setCellValue(date.toString());
                row.getCell(2).setCellValue(data.getTurnover());
                row.getCell(3).setCellValue(data.getValidOrderCount());
                row.getCell(4).setCellValue(data.getOrderCompletionRate());
                row.getCell(5).setCellValue(data.getUnitPrice());
                row.getCell(6).setCellValue(data.getNewUsers());

            }
            //通过输出流将excel文件下载到客户端浏览器
            ServletOutputStream out = httpServletResponse.getOutputStream();
            excel.write(out);
            out.flush();
            out.close();
            excel.close();
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //通过输出流将Excel文件下载到客户端
    }
}
